import FileUploader from '@/components/FileUploader';
import '@umijs/max';
import { Button, Input, message, Modal, Space, Tabs } from 'antd';
import React, { useState } from 'react';
import { uploadPictureByUrlUsingPost } from '@/services/backend/fileController';

interface Props {
  id?: string;
  visible: boolean;
  onSubmit?: () => void;
  onCancel?: () => void;
}

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const CreateModal: React.FC<Props> = (props) => {
  const { id, visible, onCancel, onSubmit } = props;
  const [url, setUrl] = useState<string>('');
  const urlUploadSubmit = async () => {
    if (!url) {
      message.error('图片链接不能为空');
    }
    try {
      await uploadPictureByUrlUsingPost({
        id: id,
        fileUrl: url,
      });
      message.success('上传成功');
    } catch (e: any) {
      message.error('上传失败:' + e.getMessage());
    } finally {
      onSubmit?.();
    }
  };
  return (
    <Modal
      destroyOnClose
      title={'上传'}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <Tabs
        defaultActiveKey="1"
        onChange={() => {}}
        items={[
          {
            label: `文件上传`,
            key: '1',
            children: <FileUploader id={id} description="图片上传" onFinish={onSubmit} />,
          },
          {
            label: `URL上传`,
            key: '2',
            children: (
              <>
                {
                  <Space.Compact style={{ width: '100%' }}>
                    <Input
                      placeholder={'请输入图片链接地址'}
                      value={url}
                      onChange={(e) => {
                        setUrl(e.target.value);
                      }}
                    />
                    <Button type="primary" onClick={urlUploadSubmit}>
                      提交
                    </Button>
                  </Space.Compact>
                }
              </>
            ),
          },
        ]}
      />
    </Modal>
  );
};
export default CreateModal;
